package cn.hello2018.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginFilter implements Filter {

	private FilterConfig filterConfig;
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;
		HttpSession session = request.getSession();

		//方法一：在web.xml中配置初始化参数，在过滤器初始化时读取，再运行时判断
		String noLoginPaths = filterConfig.getInitParameter("noLoginPaths");
		if(noLoginPaths != null) {
			String[] strArray = noLoginPaths.split(";");
			for (int i = 0; i < strArray.length; ++i) {
				if (strArray[i] == null || "".equals(strArray[i])) {
					continue;
				}
				if (request.getRequestURI().indexOf(strArray[i]) != -1) {
					arg2.doFilter(arg0, arg1);
					return;
				}
			}
		}
		
//		//方法二：登录界面直接放行
//		if (request.getRequestURI().indexOf("login.jsp") != -1 || 
//				request.getRequestURI().indexOf("login.do") != -1) {
//			arg2.doFilter(arg0, arg1);
//			return;
//		}
		
		//其他界面检查session
		if (session.getAttribute("username") != null) {
			arg2.doFilter(arg0, arg1);
		} else {
			response.sendRedirect("login.jsp");
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		filterConfig = arg0;
	}

}
